import { login, logout, getUserInfo } from "@/apis/user.js";
import { Session } from "@/utils/storage";
import rescf from "../../composables/rescf";

const user = {
  namespaced: true,
  state: {
    token: Session.get("tokenInfo")
      ? Session.get("tokenInfo").access_token
      : {},
    name: Session.get("user") ? Session.get("user").name : "",
    user: Session.get("user") ? Session.get("user") : {},
    roles: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_USER: (state, user) => {
      state.user = user;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
  },
  getters: {
    roles(state) {
      return state.roles;
    },
  },
  actions: {
    // 登录
    Login({ commit }, info) {
      // const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(info)
          .then((response) => {
            console.log(response, 'response.data.token')
            if (response.code === rescf.codeVal) {
              Session.set("tokenInfo", {
                access_token: response.data.access_token
              });
              commit("SET_TOKEN", response.data.access_token);
            }
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise(async (resolve, reject) => {
        if (!state.token) return;
        const res1 = await getUserInfo();
        if (res1.code === rescf.codeVal) {
          commit("SET_USER", res1.data);
          commit("SET_ROLES", res1.data);
          Session.set("userInfo", res1.data);
          resolve(res1.data);
        } else {
          reject();
        }
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            Session.clear();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }, cb) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        Session.clear();
        resolve();
      });
    },
  },
};

export default user;
